package com.bleeth.kettle.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.TextSimilarity;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;

import java.util.Map;


/**
 * @author BleethNie
 * @version 1.0
 * @date 2021-06-21 11:41
 **/

public class AviatorScript {


    private static AviatorEvaluatorInstance instance = AviatorEvaluator.newInstance();

    private static boolean first = true;

    private static void addStaticFunc() {
        try {
            instance.addInstanceFunctions("str", String.class);
            instance.addStaticFunctions("StrUtil", StrUtil.class);
            instance.addStaticFunctions("DateUtil", DateUtil.class);
            instance.addStaticFunctions("IdUtil", IdUtil.class);
            instance.addStaticFunctions("TextSimilarity", TextSimilarity.class);
            instance.addStaticFunctions("ReUtil", ReUtil.class);
            instance.addStaticFunctions("URLUtil", URLUtil.class);
            instance.addStaticFunctions("DigestUtil", DigestUtil.class);
            instance.addStaticFunctions("RandomUtil", RandomUtil.class);
            instance.addStaticFunctions("IdcardUtil", IdcardUtil.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行表达式
     *
     * @param expresion
     * @param paramMap
     * @return
     */
    public static Object exec(String expresion, Map<String, Object> paramMap) {
        Object obj = null;
        if (first) {
            first = false;
            addStaticFunc();
        }


        Expression exp = null;
        try {
            exp = instance.compile(expresion, true);
            if (paramMap == null) {
                obj = exp.execute();
            } else {
                obj = exp.execute(paramMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
